<?php
declare (strict_types = 1);

namespace app\common\middleware\http;

use adminmatrix\server\app\server\JsonService;
use app\common\cache\AdminAuthCache;
use think\helper\Str;
class AuthMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        if ($request->isNeedLogin)
        {
            return $next($request);
        }




        if (1 === $request->adminInfo['root'])
            return $next($request);

        $adminAuthCache = new AdminAuthCache($request->adminInfo['admin_id']);

        $allUri = $this->formatUrl($adminAuthCache->getAllUri());

        // 当前访问路径
        $accessUri = strtolower($request->controller() . '/' . $request->action());
        $accessUri = DIRECTORY_SEPARATOR . App()->http->getName() . DIRECTORY_SEPARATOR . $accessUri;
        // 判断该当前访问的uri是否存在，不存在无需验证
//        if (!in_array($accessUri, $allUri)) {
//            return $next($request);
//        }
        // 当前管理员拥有的路由权限
        $AdminUris = $adminAuthCache->getAdminUri() ?? [];
        $AdminUris = $this->formatUrl($AdminUris);

        if (in_array($accessUri, $AdminUris)) {
            return $next($request);
        }


        return JsonService::fail('权限不足，无法访问或操作');
    }

    /**
     * @notes 格式化URL
     * @param array $data
     * @return array|string[]
     * @author 段誉
     * @date 2022/7/7 15:39
     */
    public function formatUrl(array $data) : array
    {
        return array_map(function ($item) {
            return strtolower(Str::camel($item));
        }, $data);
    }

}
